﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using 简单了解Graphics操作;

namespace 简单了解Graphics操作
{
    public partial class Form7 : Form
    {
        public Form7()
        {
            InitializeComponent();
            GetCode();
        }
        public void GetCode()
        {
            //1.创建Bitmap
            Bitmap bmp = new Bitmap(140, 35);
            Graphics g = Graphics.FromImage(bmp);
            //2.绘制随机数字
            Random random = new Random();
            Color[] colors = { Color.Black, Color.Red, Color.Green, Color.Blue, Color.Coral, Color.HotPink };
            string[] codes = { "A", "B", "C", "D", "E", "F", "G", "H",
                          "a", "b", "c", "d", "e", "f", "g", "h", "0",
                          "1", "2", "3", "4", "5", "6", "7", "8", "9"};
            for(int i = 0; i < 5; i++)
            {
                g.DrawString(codes[random.Next(0, codes.Length)], new Font("微软雅黑", 10),
                            new SolidBrush(colors[random.Next(0, colors.Length)]), 
                            new PointF(i * 15 + 5, random.Next(1, 5)));
            }
            //3.绘制干扰线
            for(int i = 0; i < 12; i++)
            {
                g.DrawLine(new Pen(new SolidBrush(colors[random.Next(0, colors.Length)]), 1),
                           new Point(random.Next(0, bmp.Width), random.Next(0, bmp.Height)),
                           new Point(random.Next(0, bmp.Width), random.Next(0, bmp.Height)));
            }
            //4.绘制干扰点
            for(int i = 0; i < 300; i++)
            {
                bmp.SetPixel(random.Next(0, bmp.Width), random.Next(0, bmp.Height),
                             colors[random.Next(0, colors.Length)]);
            }
            //5.将bitmap绘制进pictureBox内
            pictureBox1.Image = bmp;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            GetCode();
        }
    }
}